package cn.iluwen.airline.Config;

import cn.iluwen.airline.Config.interceptor.AdminAuthInterceptor;
import cn.iluwen.airline.Config.interceptor.UserAuthInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * Web MVC 配置类
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    
    @Bean
    public UserAuthInterceptor userAuthInterceptor() {
        return new UserAuthInterceptor();
    }
    
    @Bean
    public AdminAuthInterceptor adminAuthInterceptor() {
        return new AdminAuthInterceptor();
    }
    
    /**
     * 配置UTF-8编码过滤器
     */
    @Bean
    public FilterRegistrationBean<CharacterEncodingFilter> filterRegistrationBean() {
        FilterRegistrationBean<CharacterEncodingFilter> registrationBean = new FilterRegistrationBean<>();
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setForceEncoding(true);
        characterEncodingFilter.setEncoding("UTF-8");
        registrationBean.setFilter(characterEncodingFilter);
        registrationBean.addUrlPatterns("/*");
        return registrationBean;
    }
    
    /**
     * 配置消息转换器，确保响应字符串的UTF-8编码
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.stream()
            .filter(converter -> converter instanceof StringHttpMessageConverter)
            .forEach(converter -> ((StringHttpMessageConverter) converter).setDefaultCharset(StandardCharsets.UTF_8));
    }
    
    /**
     * 配置内容协商，确保支持UTF-8
     */
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.defaultContentType(org.springframework.http.MediaType.APPLICATION_JSON);
    }
    
    /**
     * 配置CORS跨域支持
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")  // 使用allowedOriginPatterns替代allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .exposedHeaders("X-Admin-ID", "Set-Cookie")  // 允许前端访问的自定义响应头
                .allowCredentials(true)       // 允许发送Cookie
                .maxAge(3600);               // 预检请求的有效期，单位为秒
    }
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 用户认证拦截器
        registry.addInterceptor(userAuthInterceptor())
                .addPathPatterns("/api/v1/users/**")             // 拦截所有用户API
                .excludePathPatterns("/api/v1/users/login")      // 排除登录接口
                .excludePathPatterns("/api/v1/users/register");  // 排除注册接口
        
        // 管理员认证拦截器
        registry.addInterceptor(adminAuthInterceptor())
                .addPathPatterns("/api/v1/admin/**")             // 拦截所有管理员API
                .excludePathPatterns("/api/v1/admin/login");     // 排除登录接口
    }
}